import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:recipe/global.dart';
import 'package:recipe/http-manager.dart';
import 'package:recipe/main_manager.dart';
import 'package:recipe/utils.dart';

class DetailPage extends StatefulWidget {
  DetailPage({Key key, @required this.id}) : super(key: key);
  final String id;

  @override
  _DetailPageState createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
  Map detailData = {"foodTitle": '1'};
  @override
  void initState() {
    recipeDetail().then((res) {
      setState(() => {detailData = res});
    });
    super.initState();
  }

  recipeDetail() async {
    String url = "detail?id=${widget.id}";
    try {
      var response = await HttpUtils.request(url, method: HttpUtils.GET);
      return response["data"];
    } catch (e) {
      print(e);
    }
  }

  List<Widget> renderMaterial(renderMaterial) {
    List<Widget> list = [
      Row(
        children: [
          Text(
            "食材明细及口味：",
            maxLines: 5,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: Colors.yellow[700],
              fontSize: 16,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
      SizedBox(height: 10),
    ];
    final _m = [
      ...renderMaterial["m"],
      ...renderMaterial["f"],
      ...renderMaterial["t"]
    ];
    List.generate(_m.length, (index) {
      final item = _m[index];
      list.add(
        Container(
            width: 80,
            decoration: BoxDecoration(
                // color: Colors.yellow[700],
                border: Border.all(color: Colors.yellow[700], width: 0.5),
                borderRadius: BorderRadius.circular(5)),
            padding: EdgeInsets.all(3),
            child: Column(
              children: [
                Text(
                  "${item["name"]}",
                  style: TextStyle(
                      fontSize: 10,
                      color: Colors.black,
                      fontWeight: FontWeight.w600),
                ),
                SizedBox(height: 4),
                Text(
                  "${item["sub"]}",
                  style: TextStyle(
                      fontSize: 10,
                      color: Colors.black54,
                      fontWeight: FontWeight.w600),
                )
              ],
            )),
      );
    });
    return list;
  }

  List<Widget> renderStep(foodMethod) {
    List<Widget> list = [
      SizedBox(height: 10),
      Row(
        children: [
          SizedBox(width: 10),
          Text(
            "做法步骤：",
            maxLines: 5,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: Colors.yellow[700],
              fontSize: 16,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
      SizedBox(height: 10),
    ];
    List.generate(foodMethod.length, (index) {
      // String str = foodMethod[index];
      final item = foodMethod[index];
      list.add(
        Container(
          width: MediaQuery.of(context).size.width,
          padding: EdgeInsets.only(bottom: 10),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              SizedBox(width: 10),
              Container(
                constraints: BoxConstraints(maxWidth: 90, maxHeight: 90),
                child: ClipRRect(
                  borderRadius: BorderRadius.all(
                    Radius.circular(5),
                  ),
                  child: FadeInImage.assetNetwork(
                    placeholder: 'assets/images/placeholder.png',
                    fadeInDuration: const Duration(milliseconds: 500),
                    image: item["iSrc"],
                  ),
                ),
              ),
              SizedBox(width: 15),
              Container(
                width: 250,
                child: Text("${item["Index"]}、${item["iSub"]}",
                    maxLines: 3,
                    textAlign: TextAlign.left,
                    overflow: TextOverflow.ellipsis),
              ),
            ],
          ),
        ),
      );
    });
    return list;
  }

  @override
  Widget build(BuildContext context) {
    // MainManager _mainManager = Provider.of<MainManager>(context);
    return detailData["foodTitle"] == "1"
        ? Container(
            color: Global.backgroundColor,
            child: Center(child: CircularProgressIndicator()),
          )
        : detailData["foodTitle"] != null
            ? Scaffold(
                appBar: AppBar(
                  iconTheme: IconThemeData(color: Global.backgroundColor),
                  backgroundColor: Colors.yellow[700],
                  toolbarHeight: 40,
                  elevation: 0,
                  title: Text(
                    detailData["foodTitle"],
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontSize: 15,
                    ),
                  ),
                ),
                body: Container(
                  decoration: BoxDecoration(color: Global.backgroundColor),
                  child: SingleChildScrollView(
                    child: Column(
                      children: [
                        Container(
                          padding: EdgeInsets.all(10),
                          decoration: BoxDecoration(
                            color: Global.cardBackgroundColor,
                          ),
                          child: Column(
                            children: [
                              FadeInImage.assetNetwork(
                                  placeholder: 'assets/images/placeholder.png',
                                  fadeInDuration:
                                      const Duration(milliseconds: 500),
                                  image: detailData["foodUrl"]),
                              SizedBox(height: 10),
                              Text(detailData["foodTitle"])
                            ],
                          ),
                        ),
                        SizedBox(height: 10),
                        Container(
                          width: MediaQuery.of(context).size.width,
                          padding: EdgeInsets.all(10),
                          decoration: BoxDecoration(
                            color: Global.cardBackgroundColor,
                          ),
                          child: Wrap(
                            spacing: 5,
                            runSpacing: 10,
                            children: renderMaterial(detailData["foodStuff"]),
                          ),
                        ),
                        SizedBox(height: 10),
                        Container(
                          width: MediaQuery.of(context).size.width,
                          decoration:
                              BoxDecoration(color: Global.cardBackgroundColor),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: renderStep(detailData["foodMethod"]),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              )
            : Scaffold(
                body: Container(
                  color: Global.backgroundColor,
                  child: Center(
                    child: Text(
                      "找不到菜谱详情了，看看别的吧！",
                      style: TextStyle(
                        color: Global.fontSecondColor,
                        fontSize: 12,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ),
              );
  }
}
